package com.crazymaker.demo.hystrix;

import com.netflix.hystrix.*;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SetterDemo {
    public static HystrixCommand.Setter buildSetter(
            String groupKey, String commandKey, String threadPoolKey
    ) {
        // 与命令执行相关的一些属性集
        HystrixCommandProperties.Setter cPropertiesSetter = HystrixCommandProperties.Setter()
                // 至少有3个请求，断路器才达到熔断触发的次数阈值
                .withCircuitBreakerRequestVolumeThreshold(3)
                // 断路器触发5秒后进入half-open状态，尝试放行
                .withCircuitBreakerSleepWindowInMilliseconds(5000)
                // 错误率超过605，快速失败
                .withCircuitBreakerErrorThresholdPercentage(60)
                // 启动超时
                .withExecutionTimeoutEnabled(true)
                // 执行超时时间设定，默认1000毫秒
                .withExecutionTimeoutInMilliseconds(5000)
                // 可统计的滑动窗口内的bucket桶数，用于熔断器和指标发布
                .withMetricsRollingPercentileWindowBuckets(10)
                // 滚动窗口时间10秒，这段时间内的执行次数作为熔断器和指标发布
                .withMetricsRollingStatisticalWindowInMilliseconds(10000);

        HystrixThreadPoolProperties.Setter poolPropertiesSetter = HystrixThreadPoolProperties.Setter()
                .withCoreSize(5)
                .withMaximumSize(5);

        HystrixCommandGroupKey cGroupKey = HystrixCommandGroupKey.Factory.asKey(groupKey);
        HystrixCommandKey cCommandKey = HystrixCommandKey.Factory.asKey(commandKey);
        HystrixThreadPoolKey poolKey = HystrixThreadPoolKey.Factory.asKey(threadPoolKey);

        return HystrixCommand.Setter.withGroupKey(cGroupKey)
                .andCommandKey(cCommandKey)
                .andThreadPoolKey(poolKey)
                .andThreadPoolPropertiesDefaults(poolPropertiesSetter)
                .andCommandPropertiesDefaults(cPropertiesSetter);
    }
}
